package com.example.springbootdemo.listen;

import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;

/**
 * 异步消息队列的redis实现
 *
 * @author wuzhen on 2021/2/24
 */
@Component
public class MqByRedis {
    // 下面是基于redis的消息异步处理
    /**
     * 给景区打分
     *
     * @param receiver
     * @return
     */
    @Bean(name = "markSceneAdapter")
    public MessageListenerAdapter markSceneAdapter(Receiver receiver) {
        //指定类中回调接收消息的方法,markScene方法名
        MessageListenerAdapter adapter = new MessageListenerAdapter(receiver, "markScene");
        return adapter;
    }

    /**
     * 构建redis消息监听器容器
     */
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                                   MessageListenerAdapter markSceneAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //指定不同的方法监听不同的频道,并设立正则匹配规则
        container.addMessageListener(markSceneAdapter, new PatternTopic("markScene"));
        return container;
    }
}
